import { useMenuListStore } from '@/stores/counter'
import { dynamicMenuRoutes } from '@/router/constructRouter'
import router from '@/router/index'
import { mainRouter } from '@/router/permission'
import type { ResultTypes } from '@/resources/interface/ResultTypes'
import { nextTick } from 'vue'
import { MenuApi } from '@/apis/api/menu/MenuApi.ts'

export const constructMenuRouter = async () => {
  const menuResult: ResultTypes = await MenuApi.getMenuTreeApi()
  const children = menuResult.data
  if (mainRouter[0].children) {
    for (const child of children) {
      if (!mainRouter[0].children.find((item) => item.name === child.name)) {
        mainRouter[0].children.push(child)
      }
    }
  }

  const menuListStore = useMenuListStore()
  const menuList = dynamicMenuRoutes(mainRouter)
  menuListStore.saveMenuList(children)
  for (const menuRoute of menuList) {
    router.addRoute(menuRoute)
  }
  setTimeout(() => {}, 100)
  await nextTick()
}
